# -*- coding: utf-8 -*-
# @Time    : 2023/5/5 10:29
# @Author  : Jonny
# @File    : LuckGitlabCodeReviewService.py

import openai
from luck.gitlab.LuckGitlabApi import LuckGitlabApi


class LuckGitlabCodeReviewService(object):

    def __init__(self,
                 chatgpt_openai_api_key,
                 gitlab_private_token,
                 gitlab_server_url,
                 project_id,
                 commit_id
                 ):
        gitlab_api = LuckGitlabApi(gitlab_private_token, gitlab_server_url)

        # project
        self.project = gitlab_api.read_one_project(project_id)

        # 获取指定分支的所有commit的信息
        self.commit = gitlab_api.read_commit_by_id(commit_id)

        # changes
        self.changes = {
            'changes': self.commit.diff()
        }
        print('self.changes', self.changes)
        # openai
        openai.api_key = chatgpt_openai_api_key

        # comments
        self.review_notes = []

        # note
        self.note = ''

    def start_review(self):
        """
        self.changes = {
            'changes': [{
                'old_path': 'test/TestMap.java',
                'new_path': 'test/TestMap.java',
                'a_mode': '0',
                'b_mode': '100644',
                'new_file': True,
                'renamed_file': False,
                'deleted_file': False,
                'diff': 'Map<String, String> map = new HashMap<String, String>(); \n int num = 1000; \n for (int i = 1; i <= num; i++) { \nmap.put("" + i, "value" + i); \n } \n'
            }]
        }
        """
        print('开始code review')
        for change in self.changes['changes']:
            # https://platform.openai.com/docs/guides/chat/introduction
            messages = [
                {
                    "role": "system",
                    "content": "你是一位资深编程专家，负责代码变更的审查工作，在审查时需要给出审查建议。在建议的开始需明确对此代码变更给出「拒绝」或「接受」的决定，并且以格式「变更评分：实际的分数」给变更打分，分数区间为0~100分。然后，以精炼的语言、严厉的语气指出存在的问题。如果你觉得必要的情况下，可直接给出修改后的内容。建议中的语句可以使用emoji结尾。你的反馈内容必须使用严谨的markdown格式。"
                },
                {
                    "role": "user",
                    "content": f"请review这部分代码变更{change}",
                }
            ]

            print('思考中...')
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=messages,
            )
            new_path = change['new_path']
            print(f'对 {new_path} review中...')
            response_content = response['choices'][0]['message']['content'].replace('\n\n', '\n')
            total_tokens = response['usage']['total_tokens']

            review_note = f'# `{new_path}`' + '\n\n'
            review_note += f'({total_tokens} tokens) {"AI review 意见如下:"}' + '\n\n'
            review_note += response_content

            self.review_notes.append(review_note)

    def add_comment(self, notice=None):
        if notice is None:
            review_note = '\n\n---\n\n'.join(self.review_notes)
            self.note = {'note': review_note}
            print('self.note', self.note)
            self.commit.comments.create(self.note)
            print('review内容', self.note)
            print('review完成')
        else:
            self.note = {'note': notice}
            print('self.note', self.note)
            self.commit.comments.create(self.note)
            print(notice)
